from php4dvd.model.film import Film
from php4dvd.model.user import User
from php4dvd.model.search import Search
from php4dvd.pages.internal_page import InternalPage
from php4dvd.pages.login_page import LoginPage
from php4dvd.pages.film_add_page import FilmAddPage
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import *
import unittest, time



class Application(object):
    def __init__(self, driver, base_url):
        driver.get(base_url)
        self.wait = WebDriverWait(driver, 10)
        self.login_page = LoginPage(driver, base_url)
        self.internal_page = InternalPage(driver, base_url)

    def logout(self):
        self.internal_page.logout_button.click()
        self.wait.until(alert_is_present()).accept()

    def login(self, user):
        lp = self.login_page
        lp.is_this_page
        lp.username_field.send_keys(user.username)
        lp.password_field.send_keys(user.password)
        lp.submit_button.click()

    def add_film(self, film):
        self.internal_page.add_film_link.click()
        ump = self.film_add_page
        ump.is_this_page
        ump.film_form.title_field.send_keys(film.title)
        ump.film_form.year_field.send_keys(film.title)
        ump.film_form.submit_button.click()

    def is_error_present(self):
        return self.internal_page.is_error

    def is_added(self):
        return self.internal_page.is_added_film

    def is_film_present(self):
        self.internal_page.is_any_film
        return self.internal_page.film_count()

    def delete_film(self):
        self.internal_page.select_movie.click()
        self.internal_page.del_film_link.click()
        self.wait.until(alert_is_present()).accept()
        return self.internal_page.film_count()

    def is_film_deleted(self):
        movie_count_until=is_film_present()
        movie_count_after=delete_film()
        if movie_count_after < movie_count_until:
            return True
        else:
            return False

    def search_field_typing(self, search):
        self.internal_page.search_field.click()
        self.internal_page.search_field.send_keys(search.search_by)
        self.internal_page.search_field.send_keys(Keys.ENTER)
        time.sleep(2)

    def search_film():
        self.wait = WebDriverWait(driver, 10)
        element = self.wait.until(presence_of_element_located((By.XPATH, ".//*[@id='results']/a[1]")))
        if element.tag_name == "a":
            new_search = Search.Random()
            search_field_typing(new_search)
            is_not_found()
            return True
        else:
            return False

    def is_not_found():
        wait = WebDriverWait(driver, 10)
        element2 = wait.until(presence_of_element_located((By.XPATH, ".//*[@id='results']/div[1]")))
        if element2.tag_name == "div":
            return True
        else:
            return False